(function(){
  'use strict';

  if (!window.AppApi && !window.Api) return;
  if (window.Auth) return;

  function request(method, path, body, needAuth){
    if (window.AppApi && typeof window.AppApi.request === 'function') {
      return window.AppApi.request(method, path, body, needAuth);
    }
    if (window.Api && typeof window.Api.request === 'function') {
      return window.Api.request(method, path, body, needAuth);
    }
    throw new Error('API client not ready');
  }

  async function jsonOrThrow(res){
    if (window.AppApi && typeof window.AppApi.jsonOrThrow === 'function') return window.AppApi.jsonOrThrow(res);
    if (window.Api && typeof window.Api.jsonOrThrow === 'function') return window.Api.jsonOrThrow(res);
    if (!res.ok) throw new Error('HTTP ' + res.status);
    var ct = res.headers.get && res.headers.get('content-type');
    if (ct && ct.indexOf('application/json') >= 0) return res.json();
    return res.text();
  }

  function setToken(token){ try { localStorage.setItem('token', token); } catch(_){} }
  function getToken(){ try { return localStorage.getItem('token') || ''; } catch(_){ return ''; } }
  function clearToken(){ try { localStorage.removeItem('token'); } catch(_){} }
  function setRefreshToken(token){ try { localStorage.setItem('refresh_token', token); } catch(_){} }
  function getRefreshToken(){ try { return localStorage.getItem('refresh_token') || ''; } catch(_){ return ''; } }
  function clearRefreshToken(){ try { localStorage.removeItem('refresh_token'); } catch(_){} }

  async function login(email, password, otp){
    var payload = { email: email, password: password }; if (otp) payload.otp_code = otp;
    var res = await fetch((window.API_BASE || 'http://43.153.150.144:8080') + '/auth/login', {
      method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), credentials: 'include'
    });
    if (!res.ok) throw new Error('HTTP ' + res.status);
    var data = await res.json();
    var token = data && (data.token || data.accessToken || data.access_token || (data.data && (data.data.token || data.data.accessToken || data.data.access_token)));
    var refresh = data && (data.refresh_token || data.refreshToken || (data.data && (data.data.refresh_token || data.data.refreshToken)));
    if (!token) token = '__cookie__';
    if (token) setToken(token); if (refresh) setRefreshToken(refresh);
    return data;
  }

  function logout(){ clearToken(); clearRefreshToken(); }

  async function me(){ return await window.AppApi.jsonOrThrow(await window.AppApi.request('GET','/auth/me',null,true)); }

  function updateAuthView(){
    var token = getToken();
    var isAuthed = !!token;
    
    // 更新设置页面权限
    var settingsGuest = document.getElementById('settings-guest');
    var settingsAuthed = document.getElementById('settings-authed');
    if (settingsGuest && settingsAuthed) {
      settingsGuest.classList.toggle('is-hidden', isAuthed);
      settingsAuthed.classList.toggle('is-hidden', !isAuthed);
      if (isAuthed) {
        var hello = document.getElementById('authed-hello'); 
        if (hello) hello.textContent = '已登录';
      }
    }
    
    // 更新广播页面权限
    var broadcastGuest = document.getElementById('broadcast-guest');
    var broadcastUser = document.getElementById('broadcast-user');
    if (broadcastGuest && broadcastUser) {
      broadcastGuest.classList.toggle('is-hidden', isAuthed);
      broadcastUser.classList.toggle('is-hidden', !isAuthed);
      console.log('广播页面权限更新:', { isAuthed: isAuthed, token: !!token });
    }
  }

  window.Auth = {
    login: login,
    logout: logout,
    me: me,
    updateAuthView: updateAuthView,
    getToken: getToken,
    getRefreshToken: getRefreshToken
  };
})();


